<template>
	<view>
		<hx-navbar title="支付订单" :backgroundColor="[241, 241, 241]"></hx-navbar>
		
		
		<view class="head">
			<view class="row">
				<!-- <text v-if="countdownStr">支付剩余时间 {{ countdownStr }}</text> -->
				<!-- <text v-else>重新提交订单</text> -->
				<text >订单支付时间为3分钟，请尽快支付</text>
			</view>
			<view class="row pricebox pt-8">
				<text class="fh">￥</text>
				<text class="txt1">{{ money }}</text>
			</view>
			<view class="row pt-4" @click="doOrder">
				<text>{{ store_name }}</text>
				<!-- <text v-if="orderInfo.store_community">（{{ orderInfo.store_community }}）</text> -->
				<text>订单详情</text>
				<i class="hxicon-right"></i>
			</view>
		</view>
		<view class="container">
			<radio-group @change="payChange" class="list-box">
				<block v-for="(item, i) in payData" :key="i">
					<view class="flex-rl list-item">
						<view class="left">
							<view class="iconbox" :style="'background-color:' + item.icon_color"><i
									:class="item.icon"></i></view>
						</view>
						<view class="b-b right">
							<view class="tit-box">
								<text class="tit">{{ item.name }}</text>
							</view>
							<radio :value="item.id" color="#ffc107" :checked="item.default == 0" />
						</view>
					</view>
				</block>
			</radio-group>
		</view>

		<view class="btn tn-cool-bg-color-15--reverse" @click="JSAPIPay()">
			<text>点击微信支付</text>
		</view>

		<!-- <view class="btn" v-if="ispay" @click="showPOP()"><text>点击加食小助红包支付</text></view> -->
		<!-- <u-popup v-model="show" mode="center" @close="onClose">
			<view class="popup_box">
				<view class="qrcode">
					<image mode="widthFix" @click="previewImage()"
						src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-8a632dba-9b15-44c8-b196-f1ab51407924/c7da56d3-bf32-4b2c-8dac-b2ebfc4fb6bb.jpg">
					</image>
				</view>
				<view class="text_box_1 text-lg text-bold">您已成功上传校园卡，请关注口袋中南公众号，等待审核通知！</view>
			</view>
		</u-popup> -->
	</view>
</template>

<script>
	import md5 from '../../node_modules/crypto-js/md5.js';
	import wx from 'weixin-js-sdk';
	const db = uniCloud.database();
	let app = getApp();
	export default {
		onLoad(option) {
			let that = this;
			if (option.openid == "" || option.openid == undefined) {
				uni.showModal({
					title: "您的登录缓存已经失效，需要重新登录！",
					success(res) {
						//用户选择了登陆，直接跳转到登陆界面
						uni.switchTab({
							url: "../me/me"
						})
						return
					}
				})
			}
			//获取订单id
			if (option.id) {
				that.id = option.id;
				that.store_id = option.store_id;
				that.openid = option.openid;
				if(app.globalData.type == 'weixin'){
					that.openid = app.globalData.miniOpenid
					that.appId = "wx5189971845b7fbab"
					uni.showToast({
						content:"拿到的openid"+that.openid
					})
				}else{
					that.appId = "wxd11748aa1f038da0"
				}
				
				
				that.money = option.money
				that.expiration_date = option.expirationTime
				that.store_name = option.store_name
				console.log("订单号", that.id)
				console.log("商家号", that.store_id)
				console.log("openid号", that.openid)
				console.log("钱数", that.money)
				console.log("支付时间", that.expiration_date)
				console.log("商家名字", that.store_name)
				//可以支付A
				that.ispay = true;
				if(option.sn!=undefined){
					that.sn = option.sn
					// if(option.sn=="1"){
					// 	uni.showModal({
					// 		title:"恭喜您抽到了中南大学卡套",
					// 		success() {
					// 			return
					// 		}
					// 	})
					// }else if(option.sn=="2"){
					// 	uni.showModal({
					// 		title:"恭喜您抽到了中南大学流沙摆件",
					// 		success() {
					// 			return
					// 		}
					// 	})
					// }else if(option.sn=="3"){
					// 	uni.showModal({
					// 		title:"恭喜您抽到了中南大学签字笔",
					// 		success() {
					// 			return
					// 		}
					// 	})
					// }else{
					// 	uni.showModal({
					// 		title:"恭喜您抽到了中南大学戒指",
					// 		success() {
					// 			return
					// 		}
					// 	})
					// }
				}
			}
		},
		onReady() {},
		data() {
			return {
				ispass: "",
				oid: "",
				shownotice: false,
				numList: [{
					name: '点击支付'
				}, {
					name: '成功付款'
				}, {
					name: '点击按钮'
				}, {
					name: '跳回网站'
				}, {
					name: '订单显示'
				}, ],
				show: false,
				shixiaohzu: [],
				ispay: false,
				size: 200,
				colorDark: '#000000',
				colorLight: '#ffffff',
				canvasQrPath: '',
				QRImg: '',
				countdownStr: '00:00',
				//订单信息
				orderInfo: {},
				//默认支付方式
				payType: 'wxpay',
				appId:"",
				// 支付方式
				payData: [{
					id: 'wxpay',
					name: '微信支付',
					icon: 'hxicon-weixinzhifu',
					icon_color: '#09bb07',
					default: 0}
				// },
				// {id: 'zhifubao',
				// 	name: '支付宝支付',
				// 	icon: 'hxicon-zhifubaozhifu',
				// 	icon_color: '#00BFFF',
				// 	default: 0
				// },
				]
			};
		},
		methods: {
			confirm() {
				this.JSAPIPay()
			},
			showNotice() {
				this.shownotice = true
			},
			onClose() {
				this.show = false;
			},
			showPOP() {
				this.show = true;
			},
			previewImage() {
				this.shixiaohzu[0] =
					'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-8a632dba-9b15-44c8-b196-f1ab51407924/c7da56d3-bf32-4b2c-8dac-b2ebfc4fb6bb.jpg';
				uni.previewImage({
					current: this.shixiaohzu[0],
					urls: this.shixiaohzu
				});
			},
			//预览单张图片
			previewImg() {
				//urls为数组，数据里有多少图片链接则显示多少张，若只想预览一张的话，直接传只有一个图片地址的数组即可
				let imgurl = this.canvasQrPath;
				let imgArr = [];
				imgArr[0] = imgurl;
				uni.previewImage({
					current: 0,
					urls: imgArr
				});
			},
			payChange(event) {
				this.payType = event.target.value;
			},
			doOrder() {
				//查看订单
				uni.showModal({
					content: '这是查看订单的事件',
					showCancel: false,
					confirmColor: '#999',
					success: function(res) {}
				});
			},
			//倒计时
			countdown() {
				var go_time = new Date(this.expiration_date.replace(/-/g, '/'));
				var now_time = new Date();
				if (!go_time.getTime()) {
					return;
				}
				var alltime = go_time.getTime() - now_time.getTime(); //剩余的时间（毫秒）
				if (alltime <= 0) {
					this.countdownStr = '';
					this.showPrompt();
					return;
				}
				var haoscend = alltime % 1000; //毫秒
				//console.log(haoscend);
				var scend = parseInt((alltime / 1000) % 60);
				//console.log(scend);
				var minute = parseInt((alltime / 1000 / 60) % 60);
				// console.log(minute);
				var hour = parseInt((alltime / 1000 / 60 / 60) % 24);
				if (scend < 10) {
					scend = '0' + scend;
				}
				if (minute < 10) {
					minute = '0' + minute;
				}
				let str = minute + ':' + scend;
				if (hour > 0) {
					str = hour + ':' + str;
				}
				this.countdownStr = str;
				setTimeout(this.countdown, 1000);
			},
			//显示弹窗
			showPrompt() {
				uni.showModal({
					content: '支付超时，请重新下单',
					showCancel: false,
					confirmText: '重新下单',
					confirmColor: '#999',
					success: function(res) {
						if (res.confirm) {}
					}
				});
			},

			//判断是否在微信浏览器,true:是
			isWeiXinBrowser() {
				// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
				let ua = window.navigator.userAgent.toLowerCase();
				// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					return true;
				} else {
					return false;
				}
			},
			jsApiCall(data, callback_succ_func, callback_error_func) {
				//使用原生的，避免初始化appid问题
				console.log('准备进行微信支付了', data);
				if (data.checkPay) {
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: data.appId,
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: 'RSA',
							paySign: data.paySign
						},
						function(res) {
							var msg = res.err_msg ? res.err_msg : res.errMsg;
							switch (msg) {
								//支付成功时
								case 'get_brand_wcpay_request:ok':
									if (callback_succ_func) {
										callback_succ_func(res);
									}
									break;
								default:
									//支付失败时
									WeixinJSBridge.log('支付失败!' + msg + ',请返回重试.');
									if (callback_error_func) {
										callback_error_func({
											msg: msg
										});
									}
									break;
							}
						}
					);
				} else {
					//超过了支付时间
					uni.showModal({
						title: "您已经超过了支付时间，请重新下单",
						success(res) {
							uni.navigateTo({
								url: "../index/index"
							})
						}
					})
				}
				
			},
			
			//WeixinJSBridge判断
			wxJsPay(data, callback_succ_func, callback_error_func) {
				let that = this
				if (typeof WeixinJSBridge == 'undefined') {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
						document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
					}
				} else {
					var mini = false;
					var n=(data.package).split("=");
					uni.showModal({
						content:n[1],
						success() {
							wx.miniProgram.getEnv(function(res) {
								if (res.miniprogram) {
									//发起小程序支付
									wx.miniProgram.navigateTo({
										url: "/pages/pay/pay?appId="+data.appId+"&timeStamp="+data.timeStamp+"&nonceStr="
										+data.nonceStr+"&package="+n[1]+"&signType=RSA"+"&paySign="+data.paySign
									});
									mini = true;
								} else {
									that.jsApiCall(data, callback_succ_func, callback_error_func);
								}
							});
						}
					})
					
				}
			},
			//微信公众号支付
			async JSAPIPay() {
				let that = this;
				if(that.money==undefined||that.id==undefined||that.openid==undefined||that.openid==""){
					uni.showModal({
						title:"支付异常",
						content:"请添加食小助微信进行异常申诉",
						success(res) {
							return
						}
					})
				}else{
					uni.showLoading({
						title: '正在拉起微信支付，请稍后...'
					});
					//TODO：
					uni.request({
						url: 'https://zback.shixiaozhu.work/Shixiaozhu/order/weixinJSpay',
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset:utf-8'
						},
						method: "POST",
						data: {
							"tradeNo": that.id,
							"price": that.money,
							"description": that.store_name,
							"openid": that.openid,
							"appId":that.appId
						},
						success(res) {
							console.log("请求成功", res)
							if (true) {
								let callback_succ_func = function() {
									//清空购物车数据
									uni.removeStorageSync('shopping_cart' +
										that.store_id);
									uni.hideLoading();
									uni.navigateTo({
										url: './paySuccess?sn='+that.sn
									});
								};
								let callback_error_func = function() {
									uni.hideLoading();
									uni.showModal({
										content: '支付失败,请联系管理员！',
										showCancel: false
									});
								};
								that.wxJsPay(res.data.data, callback_succ_func,
									callback_error_func);
							} else {
								uni.showToast({
									title: res.data.message,
									icon: 'none',
									duration: 3000
								});
								return false;
							}
						}
					});
				}
				
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #f1f1f1;
	}

	.pt-8 {
		margin-top: 16rpx;
	}

	.pt-4 {
		margin-top: 8rpx;
	}

	.flex-rl {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.head {
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 60rpx 30rpx;

		.row {
			display: flex;
			flex-direction: row;
			justify-content: center;
			font-size: 24rpx;
			color: #888;

			.fh {
				font-size: 32rpx;
				font-weight: bold;
				color: #000;
			}

			.txt1 {
				font-size: 68rpx;
				font-weight: bold;
				color: #000;
			}

			[class*='hxicon-'] {
				position: relative;
				top: 6rpx;
				margin-left: 6rpx;
			}
		}

		.pricebox {
			display: flex;
			flex-direction: row;
			align-items: baseline;
		}
	}

	.container {
		margin: 30rpx;
		border-radius: 20rpx;
		background-color: #fff;
		overflow: hidden;
		padding: 0 16rpx 0 28rpx;

		.list-box {
			display: flex;
			flex-direction: column;

			.list-item {
				display: flex;
				flex-direction: row;

				align-items: center;
				height: 100rpx;

				.left {
					display: flex;
					flex-direction: row;
					align-items: center;

					.iconbox {
						display: flex;
						flex-direction: row;
						justify-content: center;
						align-items: center;
						height: 48rpx;
						width: 48rpx;
						border-radius: 8rpx;

						[class*='hxicon-'] {
							font-size: 44rpx;
							color: #fff;
						}
					}
				}

				.right {
					display: flex;
					flex-direction: row;
					align-items: center;
					flex: 1;
					height: 100%;

					.tit-box {
						flex: 1;

						.tit {
							font-size: 32rpx;
							color: #333;
							margin-left: 12rpx;
						}
					}
				}
			}
		}
	}

	.btn {
		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		border-radius: 20rpx;
		overflow: hidden;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		height: 90rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #FFFFFF;
	}

	.popup_box {
		width: 550rpx;
		height: auto;
		padding: 20rpx 20rpx;
	}

	.text_box_1 {
		display: inline;
	}

	.qrcode {
		width: 100%;
		display: flex;
		justify-content: center;
		align-content: center;
	}

	.qrcode image {
		width: 100%;
		align-self: center;
	}
</style>
